<?php
use OSS\OssClient;

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Lib/Base.php';
require_once __DIR__ . '/funcs.php';
require_once __DIR__ . '/Lib/Page.php';

checkLogin();
checkFunc(3);

$now = time();
$success = $_GET['success'] ?? null;
$error = $_GET['error'] ?? null;
$action = $_GET['action'] ?? null;
$search_type = $_POST['search_type'] ?? $_GET['search_type'] ?? null;


if($action) {
    if ($action == 'del') {
        checkFunc(4, '权限不足，无法操作');
        $aid = $_GET['id'] ?? null;
        if (!$aid) {
            $error = '无效的商品ID';
        } else {
            $DB->delete('exchanges', ['id' => $aid]);
            $success = '删除成功';
            operate_log('exchange', 'delete_item', ['商品ID' => $aid]);
        }
    }
    else if ($action == 'godown') {
        checkFunc(4, '权限不足，无法操作');
        $aid = $_GET['id'] ?? null;
        if (!$aid) $error = '无效的商品ID';
        else {
            $DB->update('exchanges', ['show'=>2], ['id' => $aid]);
            $success = '下架成功';
            operate_log('exchange', 'godown_item', ['商品ID' => $aid]);
        }
    }
    else if ($action == 'goup') {
        checkFunc(4, '权限不足，无法操作');
        $aid = $_GET['id'] ?? null;
        if (!$aid) $error = '无效的商品ID';
        else {
            $DB->update('exchanges', ['show'=>1], ['id' => $aid]);
            $success = '上架成功';
            operate_log('exchange', 'goup_item', ['商品ID' => $aid]);
        }
    }else if($action == 'onhome'){
        checkFunc(4, '权限不足，无法操作');
        $aid = $_GET['id'] ?? null;
        if (!$aid) $error = '无效的商品ID';
        else {
            $DB->update('exchanges', ['home'=>1], ['id' => $aid]);
            $success = '上首页成功';
            operate_log('exchange', 'onhome_item', ['商品ID' => $aid]);
        }
    }else if($action == 'offhome'){
        checkFunc(4, '权限不足，无法操作');
        $aid = $_GET['id'] ?? null;
        if (!$aid) $error = '无效的商品ID';
        else {
            $DB->update('exchanges', ['home'=>0], ['id' => $aid]);
            $success = '下首页成功';
            operate_log('exchange', 'offhome_item', ['商品ID' => $aid]);
        }
    }
    else if($action == 'upload') {
        checkFunc(4, '权限不足，无法操作');
        try {
            $ossclient = new OssClient($akid, $aksec, $endpoint);
            $bucket = 'kdwawajistatic';
            $name_arr = explode('.', $_FILES['file']['name']);
            $fext = $name_arr[count($name_arr)-1];
            $file_name = 'avatar_' . date('YmdHis').'_'.mt_rand(100000,999999).'.'.$fext;
            $object = 'damai/lyfen/exchangeItemAvatar/' . $file_name;
            $filePath = $_FILES['file']['tmp_name'];
            $ossclient->uploadFile($bucket, $object, $filePath);
        } catch(\Exception $e) {
            echo 'BAD|上传OSS文件失败';
            exit;
        }
        echo 'OK|'.$file_name;
        exit;
    }
    else if($action == 'new') {
        checkFunc(4, '权限不足，无法操作');
        $method = $_POST['method'] ?? null;
        if(!in_array($method, ['new', 'edit'])) {
            $error = '无效的数据类型';
        } else {
            $edit_id = $_POST['edit_id'] ?? null;
            $product_id = $_POST['new_product_id'] ?? null;
            $avatar = $_POST['oss_filename'] ?? null;
            $name = $_POST['new_name'] ?? null;
            $desc = $_POST['new_desc'] ?? null;
            $need_star = $_POST['new_need_star'] ?? null;
            $type = $_POST['new_type'] ?? null;
            $stype = $_POST['new_stype'] ?? null;
            $price = $_POST['new_price'] ?? null;
            $invenroty = $_POST['new_inventory'] ?? 0;
            $effective = $_POST['effective'] ?? 0;
            $sort = $_POST['sort'] ?? 0;
            $home = $_POST['home'] ?? 0;
            $isMaterial = $_POST['isMaterial'] ?? 0;
            $sname = $_POST['sname'] ?? '';
            $origin_price = $_POST['origin_price'] ?? '';
            $jump = $_POST['jump'] ?? '';
            $product_id = trim($product_id);
            if ($avatar){
                $avatar = $CDN_URL . '/exchangeItemAvatar/' . $avatar;
            }
            if($method == 'edit' && $edit_id) {
                $DB->update('exchanges', [
                    'productId' => $product_id,
                    'avatar' => $avatar,
                    'name' => $name,
                    'desc' => $desc,
                    'needStar' => $need_star,
                    'type' => $type,
                    'stype' => $stype,
                    'price' => $price,
                    'inventory' => $invenroty,
                    'effective' => $effective,
                    'sort' => $sort,
                    'home' => $home,
                    'isMaterial' => $isMaterial,
                    'sname' => $sname,
                    'origin_price' => $origin_price,
                    'jump' => $jump,
                ], ['id'=>$edit_id]);
                operate_log('exchange', 'edit_item', [
                    '商品ID' => $edit_id, '批次号' => $product_id, '名称' => $name, '介绍' => $desc, '花费星星' => $need_star, '类型' => $type, '子类型' => $stype, '价值' => $price, '库存'=>$invenroty
                ]);
                $success = '商品信息修改成功';
            } else {
                $DB->insert('exchanges', [
                    'productId' => $product_id,
                    'avatar' => $avatar,
                    'name' => $name,
                    'desc' => $desc,
                    'needStar' => $need_star,
                    'type' => $type,
                    'stype' => $stype,
                    'price' => $price,
                    'inventory' => $invenroty,
                    'show' => 1,
                    'effective' => $effective,
                    'sort' => $sort,
                    'home' => $home,
                    'isMaterial' => $isMaterial,
                    'sname' => $sname,
                    'origin_price' => $origin_price,
                    'jump' => $jump,
                ]);
                $id = $DB->id();
                if (!$id) $error = '创建商品失败';
                else {
                    $success = '添加商品成功';
                    operate_log('exchange', 'new_item', [
                        '商品ID' => $id, '批次号' => $product_id, '名称' => $name, '介绍' => $desc, '花费星星' => $need_star, '类型' => $type, '子类型' => $stype, '价值' => $price, '库存'=>$invenroty
                    ]);
                }
            }
        }
    }
    else if($action == 'getNext'){
        $type_id = $_POST['type_id'] ?? 0;
        if (!$type_id) $json = ['code' => 500,'data' => []];
        else{
            $all_children = $DB->select('exchange_type_children', ['id','children_name'], ['type_id' => $type_id]);
            $json = ['code' => 200,'data' => $all_children];
        }
        echo json_encode($json,256);
        exit;
    }
    else if($action == 'effective'){
        $type_id = $_POST['type_id'] ?? 0;
        if (!$type_id) $json = ['code' => 500,'data' => []];
        else{
            $effective = $DB->get('exchange_type','*',['id' => $type_id]);
            $json = ['code' => 200,'data' => $effective];
        }
        echo json_encode($json,256);
        exit;
    }
    else {
        $error = '无效的操作';
    }
    goExit('exchange_item.php?success=' . $success . '&error=' . $error.'&types='.$search_type);
}

display_header();

$types = $_GET['types'] ?? null;
$item_where = ['ORDER'=>['id'=>'DESC']];
if ($types){
    $item_where['type'] = $types;
}
$all_items = $DB->select('exchanges', '*',$item_where);
if ($all_items){
    $type_ids = array_column($all_items,'type');
    $type_array = $DB->select('exchange_type', ['id','type_name'], ['id' => $type_ids]);
    $children_ids = array_column($all_items,'stype');
    $children_array = $DB->select('exchange_type_children', ['id','children_name'], ['id' => $children_ids]);
    foreach ($all_items as &$z){
        $z['type_name'] = '';
        if ($type_array){
            foreach ($type_array as $v){
                if ($z['type'] == $v['id']){
                    $z['type_name'] = $v['type_name'];
                }
            }
        }
        $z['children_name'] = '';
        if ($children_array){
            foreach ($children_array as $val){
                if ($z['stype'] == $val['id']){
                    $z['children_name'] = $val['children_name'];
                }
            }
        }
    }
}

//$type_arr = [0=>'实物', 1=>'优惠券'];
//$stype_arr = [1=>'1类兑换券', 2=>'2类兑换券', 3=>'3类兑换券'];

$type_arr = $DB->select('exchange_type', '*');
?>

<link href="css/jquery.dm-uploader.min.css" rel="stylesheet">
<style>
    #fileinp{
        position: absolute;
        left: 0;
        top: 0;
        opacity: 0;
    }
</style>

<section class="content">
    <?php if($error) : ?>
        <div class="alert alert-warning alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
            <span><?php echo $error; ?></span>
        </div>
    <?php endif ?>
    <?php if($success) : ?>
        <div class="alert alert-success alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            <h4><i class="icon fa fa-check"></i> 成功</h4>
            <?php echo $success; ?>
        </div>
    <?php endif ?>

    <div class="box box-primary">
        <div class="box-header with-border">
            <h3 class="box-title"><i class="fa fa-search"></i> 兑换商品</h3>
        </div>

        <div class="box-body" id="vbody">

            <button type="button" class="btn btn-primary pull-left new_item" style="margin-bottom:10px;">添加兑换商品</button>
            <div class="">
                <div class="line">
                    <form action="exchange_item.php" method="get">
                        <div class="pull-left" style="padding:0px 15px; display:inline-block;line-height:32px;">
                            <div class="pull-left">优惠券类型:&nbsp;&nbsp;</div>
                            <select class="form-control" name="types" style="display:inline !important;float:left;width:auto;">
                                <option value=""></option>
                                <?php foreach ($type_arr as $val){ ?>
                                    <option value="<?php echo $val['id'] ?>" <?php if ($types == $val['id']){ ?> selected <?php }?>><?php echo $val['type_name']; ?></option>
                                <?php }?>
                            </select>
                        </div>
                        <button type="submit" class="btn btn-primary pull-left">查看数据</button>
                    </form>
                </div>
            </div>

            <table id="logtable" class="table table-bordered table-striped dataTable table-hover " role="grid" aria-describedby="example1_info">
                <thead>
                <tr>
                    <th class="" rowspan="1" colspan="1" width="60" style="text-align:center">ID</th>
                    <th class="" rowspan="1" colspan="1" width="60" style="text-align:center">排序</th>
                    <th class="" rowspan="1" colspan="1" width="60" style="text-align:center">首页显示</th>
                    <th class="" rowspan="1" colspan="1" width="60" style="text-align:center">是否实物</th>
                    <th class="" rowspan="1" colspan="1" width="100" style="text-align:center;">商品批次号</th>
                    <th class="" rowspan="1" colspan="1" width="70" style="text-align:center;">图标</th>
                    <th class="" rowspan="1" colspan="1" width="150">名称</th>
                    <th class="" rowspan="1" colspan="1" width="200" style="text-align:center">介绍</th>
                    <th class="" rowspan="1" colspan="1" width="90" style="text-align:center">花费星星</th>
                    <th class="" rowspan="1" colspan="1" width="90" style="text-align:center">类型</th>
                    <th class="" rowspan="1" colspan="1" width="100" style="text-align:center">子类</th>
                    <th class="" rowspan="1" colspan="1" width="100" style="text-align:center">类型名称</th>
                    <th class="" rowspan="1" colspan="1" width="100" style="text-align:center">有效期</th>
                    <th class="" rowspan="1" colspan="1" width="80" style="text-align:center">券后价</th>
                    <th class="" rowspan="1" colspan="1" width="80" style="text-align:center">原价</th>
                    <th class="" rowspan="1" colspan="1" width="80" style="text-align:center">剩余库存</th>
                    <th class="" rowspan="1" colspan="1" width="80" style="text-align:center">跳转地址</th>
                    <th class="" rowspan="1" colspan="1" style="text-align:center">操作</th>
                </tr>
                </thead>
                <tbody>
                <?php if(!empty($all_items)) { foreach($all_items as $item) { ?>
                    <tr role="row" style="text-align:center;">
                        <td class="item_id"><?php echo $item['id']; ?></td>
                        <td class="item_sort"><?php echo $item['sort']; ?></td>
                        <td class="item_home" data-home="<?php echo $item['home'] ?>"><?php echo $item['home'] == 1 ? '是':'否'; ?></td>
                        <td class="item_isMaterial" data-isMaterial="<?php echo $item['isMaterial'] ?>"><?php echo $item['isMaterial'] == 1 ? '是':'否'; ?></td>
                        <td class="item_productId"><?php echo $item['productId']; ?></td>
                        <td class="item_avatar" style="font-size:12px;">
                            <?php
                            if(strpos($item['avatar'], '.') !== false) {
                                echo '<img src="'.$item['avatar'].'" width="60" height="60" />';
                            } else echo $item['avatar'];
                            ?>
                        </td>
                        <td class="item_name" style="text-align:left;font-size:16px;"><?php echo $item['name']; ?></td>
                        <td class="item_desc" style="font-size:10px;"><?php echo $item['desc']; ?></td>
                        <td class="item_needStar"><?php echo $item['needStar']; ?></td>
                        <td class="item_type" typeid="<?php echo $item['type']; ?>"><?php echo $item['type_name']; ?></td>
                        <td class="item_stype" typeid="<?php echo $item['stype']; ?>"><?php echo $item['children_name']; ?></td>
                        <td class="item_sname"><?php echo $item['sname']; ?></td>
                        <td class="item_effective"><?php echo $item['effective']; ?></td>
                        <td class="item_price"><?php echo $item['price']; ?></td>
                        <td class="item_origin_price"><?php echo $item['origin_price']; ?></td>
                        <td class="item_inventory"><?php echo $item['inventory']; ?></td>
                        <td class="item_jump"><?php echo $item['jump']; ?></td>
                        <td style="text-align:left;">
                            <button type="button" class="btn btn-sm btn-success edit_item">修改</button> |
                            <?php if($item['show']==1) { ?><button type="button" class="btn btn-sm btn-warning godown" iid="<?php echo $item['id']; ?>">下架</button> |<?php } ?>
                            <?php if($item['show']==2) { ?><button type="button" class="btn btn-sm btn-success goup" iid="<?php echo $item['id']; ?>">上架</button> |<?php } ?>
                            <?php if($item['home']==1) { ?><button type="button" class="btn btn-sm btn-warning offhome" iid="<?php echo $item['id']; ?>">下首页</button> |<?php } ?>
                            <?php if($item['home']==0) { ?><button type="button" class="btn btn-sm btn-success onhome" iid="<?php echo $item['id']; ?>">上首页</button> |<?php } ?>
                            <button type="button" class="btn btn-sm btn-danger del_notice" iid="<?php echo $item['id']; ?>">删除</button>
                        </td>
                    </tr>
                <?php } } ?>
                </tbody>
            </table>

            <!-- 添加兑换商品 -->
            <div class="modal fade" id="modal-add-admin">
                <div class="modal-dialog modal-lg">
                    <form id="item_form" action="exchange_item.php?action=new" method="post">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span></button>
                                <h4 class="modal-title">添加兑换商品</h4>
                            </div>
                            <div class="modal-body">
                                <input type="hidden" id="new_method" name="method" value="new" />
                                <input type="hidden" id="edit_id" name="edit_id" value="" />
                                <input type="hidden" id="search_type" name="search_type" value="<?php echo $types; ?>" />
                                <table border="0" width="100%" class="modal_table_style">
                                    <tr height="45">
                                        <th style="text-align:right;padding-right:10px;">批次号:</th>
                                        <td><input type="text" class="form-control" size="20" name="new_product_id" id="new_product_id" /></td>
                                    </tr>
                                    <tr height="110">
                                        <th style="text-align:right;padding-right:10px;">图标:</th>
                                        <td>
                                            <img style="float:left;border:1px solid #aaa;" id="avatar_preview" src="images/noimage.jpg" width="100" height="100" />
                                            <div id="drop-area" style="float:left; padding-top:40px; margin-left:20px;">
                                                <label for="fileinp">
                                                    <span id="text" style="padding:10px 20px;border-radius:4px;background:#007bff;color:#fff;">请上传图片</span>
                                                    <input type="file" id="fileinp" />
                                                    <br />
                                                    <div style="margin-top:15px;font-size:12px;font-weight:normal;" id="upload_result"></div>
                                                    <input type="hidden" id="oss_filename" name="oss_filename" value="" />
                                                </label>
                                            </div>
                                        </td>
                                    </tr>
                                    <tr height="45">
                                        <th style="text-align:right;padding-right:10px;">名称:</th>
                                        <td><input type="text" class="form-control" size="20" name="new_name" id="new_name" /></td>
                                    </tr>
                                    <tr height="45">
                                        <th style="text-align:right;padding-right:10px;">介绍:</th>
                                        <td><textarea class="form-control" size="20" rows="7" name="new_desc" id="new_desc"></textarea></td>
                                    </tr>
                                    <tr height="45">
                                        <th style="text-align:right;padding-right:10px;">花费星星:</th>
                                        <td><input type="text" class="form-control" size="20" name="new_need_star" id="new_need_star" /></td>
                                    </tr>
                                    <tr height="45">
                                        <th width="150" style="text-align:right;padding-right:10px;">类型:</th>
                                        <td>
                                            <select class="form-control" id="new_type" name="new_type" style="width:100%;" onchange='btnChange(this[selectedIndex].value);'>
                                                <option value=""></option>
                                                <?php foreach($type_arr as $t) : ?>
                                                    <option value="<?php echo $t['id']; ?>"><?php echo $t['id'] . ' - ' . $t['type_name']; ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </td>
                                    </tr>
                                    <tr height="45">
                                        <th width="150" style="text-align:right;padding-right:10px;">子类型:</th>
                                        <td>
                                            <select class="form-control" id="new_stype" name="new_stype" style="width:100%;">
                                                <option value=""></option>
                                            </select>
                                        </td>
                                    </tr>
                                    <tr height="45">
                                        <th style="text-align:right;padding-right:10px;">类型名称:</th>
                                        <td><input type="text" class="form-control" size="20" name="sname" id="sname" /></td>
                                    </tr>
                                    <tr height="45" class="effective_type" style="display: none">
                                        <th style="text-align:right;padding-right:10px;">有效期:</th>
                                        <td><input type="text" class="form-control" size="20" name="effective" id="effective" /></td>
                                    </tr>
                                    <tr height="45">
                                        <th style="text-align:right;padding-right:10px;">原价:</th>
                                        <td><input type="text" class="form-control" size="20" name="origin_price" id="origin_price" /></td>
                                    </tr>
                                    <tr height="45">
                                        <th style="text-align:right;padding-right:10px;">券后价:</th>
                                        <td><input type="text" class="form-control" size="20" name="new_price" id="new_price" /></td>
                                    </tr>
                                    <tr height="45">
                                        <th style="text-align:right;padding-right:10px;">库存:</th>
                                        <td><input type="text" class="form-control" size="20" name="new_inventory" id="new_inventory" /></td>
                                    </tr>
                                    <tr height="45">
                                        <th style="text-align:right;padding-right:10px;">排序:</th>
                                        <td><input type="text" class="form-control" size="20" name="sort" id="sort" value="0" /></td>
                                    </tr>
                                    <tr height="45">
                                        <th style="text-align:right;padding-right:10px;">首页显示:</th>
                                        <td>
                                            <input type="radio" id="home1" name="home" value="1" />是
                                            <input type="radio" id="home2" name="home" value="0" />否
                                        </td>
                                    </tr>
                                    <tr height="45">
                                        <th style="text-align:right;padding-right:10px;">是否实物:</th>
                                        <td>
                                            <input type="radio" id="isMaterial1" name="isMaterial" value="1" />是
                                            <input type="radio" id="isMaterial2" name="isMaterial" value="0" />否
                                        </td>
                                    </tr>
                                    <tr height="45">
                                        <th style="text-align:right;padding-right:10px;">跳转地址:</th>
                                        <td><input type="text" class="form-control" size="20" name="jump" id="jump" value="" /></td>
                                    </tr>
                                </table>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default pull-left" data-dismiss="modal">取消</button>
                                <button type="button" class="btn btn-primary submit_form">确定</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

        </div>

    </div>
</section>

<!-- jQuery 3 -->
<script src="js/jquery.min.js"></script>
<script src="js/jquery.cookie.js"></script>
<script src="js/pace.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Select2 -->
<script src="bower_components/select2/dist/js/select2.full.min.js"></script>
<!-- InputMask -->
<script src="plugins/input-mask/jquery.inputmask.js"></script>
<script src="plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
<script src="plugins/input-mask/jquery.inputmask.extensions.js"></script>

<script src="js/jquery.dm-uploader.min.js"></script>

<script type="text/javascript">

    $(function() {
        $('.new_item').click(function() {
            $('.modal-title').text('添加兑换商品');
            $('#new_method').val('new');
            $('#edit_id').val('');
            $('#new_product_id').val('');
            $('#avatar_preview').attr('src', 'images/noimage.jpg');
            $('#oss_filename').val('');
            $('#new_name').val('');
            $('#sname').val('');
            $('#sort').val('');
            $('#effective').val('');
            $('#new_desc').val('');
            $('#new_need_star').val('');
            $("#new_type option").each(function() {
                if($(this).text().length < 1) {
                    $(this).attr('selected', true);
                }
            });
            $('select[name=new_stype]').empty();
            $("#new_stype option").each(function() {
                if($(this).text().length < 1) {
                    $(this).attr('selected', true);
                }
            });
            $('#new_price').val('');
            $('#jump').val('');
            $('#origin_price').val('');
            $('#new_inventory').val('');
            $('#modal-add-admin').modal({
                backdrop: 'static',
            });
        });
        $('.edit_item').click(function() {
            $('.modal-title').text('修改商品信息');
            $('#new_method').val('edit');
            var id = $(this).parent().parent().find('.item_id').text();
            var product_id = $(this).parent().parent().find('.item_productId').text();
            var avatar = $(this).parent().parent().find('img').attr('src');
            var name = $(this).parent().parent().find('.item_name').text();
            var desc = $(this).parent().parent().find('.item_desc').text();
            var needStar = $(this).parent().parent().find('.item_needStar').text();
            var type = $(this).parent().parent().find('.item_type').text();
            var type_id = $(this).parent().parent().find('.item_type').attr('typeid');
            var stype = $(this).parent().parent().find('.item_stype').text();
            var stype_id = $(this).parent().parent().find('.item_stype').attr('typeid');
            var effective = $(this).parent().parent().find('.item_effective').text();
            var price = $(this).parent().parent().find('.item_price').text();
            var inventory = $(this).parent().parent().find('.item_inventory').text();
            var sort = $(this).parent().parent().find('.item_sort').text();
            var home = $(this).parent().parent().find('.item_home').attr('data-home');
            var isMaterial = $(this).parent().parent().find('.item_isMaterial').attr('data-isMaterial');
            var sname = $(this).parent().parent().find('.item_sname').text();
            var origin_price = $(this).parent().parent().find('.item_origin_price').text();
            var jump = $(this).parent().parent().find('.item_jump').text();
            $('#jump').val(jump);
            if (home == 1){
                $('#home1').prop('checked',true);
            }else{
                $('#home2').prop('checked',true);
            }
            if (isMaterial == 1){
                $('#isMaterial1').prop('checked',true);
            }else{
                $('#isMaterial2').prop('checked',true);
            }
            $('#sort').val(sort);
            $('#sname').val(sname);
            $('#origin_price').val(origin_price);
            $('#new_product_id').val(product_id);
            if(avatar && avatar.indexOf('.') != -1) {
                $('#avatar_preview').attr('src', avatar);
                var avatar_arr = avatar.split('/');
                var arr_len = avatar_arr.length - 1;
                $('#oss_filename').val(avatar_arr[arr_len]);
            }
            $('#new_name').val(name);
            $('#new_desc').val(desc);
            $('#new_need_star').val(needStar);
            //类型选中
            $("#new_type option").each(function() {
                let selected = false;
                if($(this).val() == type_id) {
                    selected = true;
                }
                $(this).attr('selected', selected);
            });
            //子类选中
            $.ajax({
                type: "post",
                url:'exchange_item.php?action=getNext',
                dataType: "json",
                data:{type_id:type_id},
                success: function(res, textStatus, request){
                    $('select[name=new_stype]').empty();
                    if(res.code == 200){
                        let str = '';
                        res.data.forEach(function (v,k) {
                            let selected = '';
                            if (v.id == stype_id){
                                selected = 'selected';
                            }
                            str += '<option value="'+v.id+'" '+selected+'>'+v.id+' - '+v.children_name+'</option>\n'
                        });
                        $('select[name=new_stype]').append(str);
                    }else{
                        alert('请选择类型');
                    }
                }
            });

            // $("#new_stype option").each(function() {
            //     if($(this).val() == stype_id) {
            //         $(this).attr('selected', true);
            //     }
            // });
            if (effective != 0){
                $('.effective_type').show();
                $('#effective').val(effective);
            }else{
                $('.effective_type').hide();
                $('#effective').val('');
            }
            $('#new_price').val(price);
            $('#new_inventory').val(inventory);
            $('#edit_id').val(id);
            $('#modal-add-admin').modal({
                backdrop: 'static',
            });
        });
        $('.submit_form').click(function() {
            $('#item_form').submit();
        });
        $('.del_notice').click(function() {
            if(confirm('确认删除该商品吗？\n\n！！！！！ 该操作不可恢复 ！！！！！\n\n')) {
                var iid = $(this).attr('iid');
                var search_type = $('#search_type').val();
                location.href = 'exchange_item.php?action=del&id=' + iid +'&search_type='+search_type;
            }
        });
        $('.godown').click(function() {
            var iid = $(this).attr('iid');
            var search_type = $('#search_type').val();
            location.href = 'exchange_item.php?action=godown&id=' + iid+'&search_type='+search_type;
        });
        $('.goup').click(function() {
            var iid = $(this).attr('iid');
            var search_type = $('#search_type').val();
            location.href = 'exchange_item.php?action=goup&id=' + iid+'&search_type='+search_type;
        });

        $('.onhome').click(function() {
            var iid = $(this).attr('iid');
            var search_type = $('#search_type').val();
            location.href = 'exchange_item.php?action=onhome&id=' + iid+'&search_type='+search_type;
        });

        $('.offhome').click(function() {
            var iid = $(this).attr('iid');
            var search_type = $('#search_type').val();
            location.href = 'exchange_item.php?action=offhome&id=' + iid+'&search_type='+search_type;
        });

        $("#drop-area").dmUploader({
            url: 'exchange_item.php?action=upload',
            multiple: false,
            maxFileSize: 3000000,
            allowedTypes: 'image/*',
            extFilter: ['jpg','jpeg','png','gif'],
            onInit: function(){
                console.log('Callback: Plugin initialized');
            },
            onNewFile: function(id, file){
                // When a new file is added using the file selector or the DnD area
                console.log('New file added #' + id);
                if (typeof FileReader !== "undefined"){
                    var reader = new FileReader();
                    var img = $('#avatar_preview');
                    reader.onload = function (e) {
                        img.attr('src', e.target.result);
                    }
                    reader.readAsDataURL(file);
                }
            },
            onBeforeUpload: function(id){
                console.log('start upload ... ' + id);
            },
            onUploadProgress: function(id, percent){
                console.log(id + ' uploading ... ' + percent);
            },
            onUploadSuccess: function(id, data){
                var darr = data.split('|');
                if(darr[0] != 'OK') {
                    alert(darr[1]);
                } else {
                    $('#upload_result').text('图片上传成功，文件名：' + darr[1]);
                    $('#oss_filename').val(darr[1]);
                }
            },
            onUploadError: function(id, xhr, status, message){
                alert('图片上传失败，请联系管理员');
            },
            onFileSizeError: function(file){
                alert('图片不可超过3M');
            },
            onFileTypeError: function(file){
                alert('图片类型错误');
            },
            onFileExtError: function(file){
                alert('图片扩展名错误');
            }
        });

        setTimeout(function() {
            $('.alert-success').fadeOut();
            if($('.alert-warning').find('span').html() && $('.alert-warning').find('span').html().length < 60) {
                $('.alert-warning').fadeOut();
            }
        }, 2000);

        // $('#new_type').change(function (e) {
        //     console.log(e.options[this.options.selectedIndex].value);
        // })
    });

    //获取下级分类
    function btnChange(val){
        $.ajax({
            type: "post",
            url:'exchange_item.php?action=getNext',
            dataType: "json",
            data:{type_id:val},
            success: function(res, textStatus, request){
                $('select[name=new_stype]').empty();
                if(res.code == 200){
                    let str = '';
                    res.data.forEach(function (v,k) {
                        str += '<option value="'+v.id+'" >'+v.id+' - '+v.children_name+'</option>\n'
                    });
                    $('select[name=new_stype]').append(str);
                }else{
                    alert('请选择类型');
                }
            }
        });

        $.ajax({
            type: "post",
            url:'exchange_item.php?action=effective',
            dataType: "json",
            data:{type_id:val},
            success: function(res, textStatus, request){
                if(res.code == 200){
                    if (res.data.effective_status == 1){
                        $('.effective_type').show();
                    }else{
                        $('.effective_type').hide();
                    }
                }
            }
        });
    }
</script>

</body>
</html>

